package wu2020.top.compare.orm.demo.infrastructure.persistence.easy_query;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.mysql.expression.MySQLInsertSQLExpression;
import com.wu.framework.inner.lazy.database.expand.database.persistence.domain.LazyPage;
import com.wu.framework.response.Result;
import com.wu.framework.response.ResultFactory;
import jakarta.annotation.Resource;
import org.sagacity.sqltoy.model.EntityQuery;
import org.sagacity.sqltoy.model.Page;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import wu2020.top.compare.orm.demo.domain.model.sys.user.ORMComparisonRepository;
import wu2020.top.compare.orm.demo.domain.model.sys.user.SysUser;
import wu2020.top.compare.orm.demo.infrastructure.converter.SysUserConverter;
import wu2020.top.compare.orm.demo.infrastructure.entity.SysUserDO;
import wu2020.top.compare.orm.demo.infrastructure.persistence.SysUserRepositoryAbstractRecord;
import wu2020.top.compare.orm.demo.infrastructure.persistence.enums.Orm;
import wu2020.top.compare.orm.demo.infrastructure.persistence.enums.Type;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe sys_user
 *
 * @author Jia wei Wu
 * @date 2024/02/28 11:27 上午
 * @see com.wu.framework.inner.lazy.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Component("easy_query")
public class EasyQueryComparisonRepository extends SysUserRepositoryAbstractRecord implements ORMComparisonRepository {


    @Resource
    EasyQuery easyQuery;

    /**
     * describe 新增
     *
     * @param sysUser 新增
     * @return {@link Result<SysUser>} 新增后领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> story(SysUser sysUser) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        try {
            SysUserDO sysUserDO = SysUserConverter.INSTANCE.fromSysUser(sysUser);

            // 遇到唯一性索引 用户名、scope
            easyQuery.insertable(sysUserDO).onDuplicateKeyUpdate().executeRows();

        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.story, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增
     *
     * @param sysUserList 批量新增
     * @return {@link Result<List<SysUser>>} 新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> batchStory(List<SysUser> sysUserList) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        try {
            List<SysUserDO> sysUserDOList = sysUserList.stream().map(SysUserConverter.INSTANCE::fromSysUser).collect(Collectors.toList());
            easyQuery.insertable(sysUserDOList).onDuplicateKeyIgnore().executeRows();
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.batchStory, startTime, endTime, sysUserList.size(), success);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个
     *
     * @param sysUser 查询单个
     * @return {@link Result<SysUser>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> findOne(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findOne(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        SysUser one = null;
        try {
            // .... 将条件逐个添加
            one = easyQuery.queryable(SysUserDO.class)
                    .where(
                            sysUserDOSQLWherePredicate ->
                                    sysUserDOSQLWherePredicate.eq(sysUser.getId() != null, SysUserDO::getId, sysUser.getId())
                                            .eq(sysUser.getIsDeleted() != null, SysUserDO::getIsDeleted, sysUser.getIsDeleted())
                                            .like(sysUser.getUsername() != null, SysUserDO::getUsername, sysUser.getUsername())

                    )
                    .firstNotNull(SysUser.class);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.findOne, startTime, endTime, success);
        return ResultFactory.successOf(one);
    }

    /**
     * describe 查询多个
     *
     * @param sysUser 查询多个
     * @return {@link Result<List<SysUser>>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> findList(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findList(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        List<SysUser> sysUserList = new ArrayList<>();
        try {
            EntityQuery entityQuery = EntityQuery.create();
            entityQuery.where("id").values(sysUser.getId());
            entityQuery.where("is_deleted").values(sysUser.getIsDeleted());
            if (!ObjectUtils.isEmpty(sysUser.getUsername())) {
                entityQuery.where("username like ").values(sysUser.getUsername());
            }
            // .... 将条件逐个添加
            sysUserList = easyQuery.queryable(SysUserDO.class)
                    .where(
                            sysUserDOSQLWherePredicate ->
                                    sysUserDOSQLWherePredicate.eq(sysUser.getId() != null, SysUserDO::getId, sysUser.getId())
                                            .eq(sysUser.getIsDeleted() != null, SysUserDO::getIsDeleted, sysUser.getIsDeleted())
                                            .like(sysUser.getUsername() != null, SysUserDO::getUsername, sysUser.getUsername())

                    )
                    .toList(SysUser.class);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.findList, startTime, endTime, success);

        return ResultFactory.successOf(sysUserList);
    }

    /**
     * describe 分页查询多个
     *
     * @param size    当前页数
     * @param current 当前页
     * @param sysUser 分页查询多个
     * @return {@link Result<LazyPage<SysUser>>} 分页领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<LazyPage<SysUser>> findPage(int size, int current, SysUser sysUser) throws Exception {
        boolean success = true;
        super.findPage(size, current, sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        LazyPage<SysUser> lazyPage = new LazyPage<>(current, size);
        try {

            EasyPageResult<SysUser> pageResult = easyQuery.queryable(SysUserDO.class)
                    .where(
                            sysUserDOSQLWherePredicate ->
                                    sysUserDOSQLWherePredicate.eq(sysUser.getId() != null, SysUserDO::getId, sysUser.getId())
                                            .eq(sysUser.getIsDeleted() != null, SysUserDO::getIsDeleted, sysUser.getIsDeleted())
                                            .like(sysUser.getUsername() != null, SysUserDO::getUsername, sysUser.getUsername())

                    )
                    .toPageResult(SysUser.class, current, size);

            // .... 将条件逐个添加
            lazyPage.setTotal(pageResult.getTotal());
            lazyPage.setRecord(pageResult.getData());
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.findPage, startTime, endTime, size, success);
        return ResultFactory.successOf(lazyPage);
    }

    /**
     * describe 删除
     *
     * @param sysUser 删除
     * @return {@link Result<SysUser>}
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> remove(SysUser sysUser) throws Exception {
        boolean success = true;
        super.remove(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        try {
            EntityQuery entityQuery = EntityQuery.create();
            entityQuery.where("id").values(sysUser.getId());
            entityQuery.where("is_deleted").values(sysUser.getIsDeleted());
            if (!ObjectUtils.isEmpty(sysUser.getUsername())) {
                entityQuery.where("username like ").values(sysUser.getUsername());
            }
            easyQuery.deletable(SysUserDO.class)
                    .where(
                            sysUserDOSQLWherePredicate ->
                                    sysUserDOSQLWherePredicate.eq(sysUser.getId() != null, SysUserDO::getId, sysUser.getId())
                                            .eq(sysUser.getIsDeleted() != null, SysUserDO::getIsDeleted, sysUser.getIsDeleted())
                                            .like(sysUser.getUsername() != null, SysUserDO::getUsername, sysUser.getUsername())

                    ).executeRows();
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.remove, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在
     *
     * @param sysUser 领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<Boolean> exists(SysUser sysUser) throws Exception {
        boolean success = true;
        super.exists(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        Long count = 0L;
        try {
            count = easyQuery.queryable(SysUserDO.class)
                    .where(
                            sysUserDOSQLWherePredicate ->
                                    sysUserDOSQLWherePredicate.eq(sysUser.getId() != null, SysUserDO::getId, sysUser.getId())
                                            .eq(sysUser.getIsDeleted() != null, SysUserDO::getIsDeleted, sysUser.getIsDeleted())
                                            .like(sysUser.getUsername() != null, SysUserDO::getUsername, sysUser.getUsername())

                    ).count();
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.EASY_QUERY, Type.exists, startTime, endTime, success);
        return ResultFactory.successOf(count > 0);
    }

}